import React, { useEffect, useState } from "react";
import style from "./style.less"
import { changeAccount, changeAvatarHandle, getFocuseInfo, getUserInfo } from "../../service/account";
import userStore from "../../store/user";
import NoAvatar from "../../source/svgs/noavatar.svg";
import { Empty, Input, message, Popconfirm, Radio } from "antd";
import { ChangeAccount, IChangeAvatar, originUserInfo, UserInfo } from "../../interface/account";
import { formatTime, myTip } from "../../tools/publicFun";
import { useNavigate } from "react-router-dom";
import cookieStore from "../../store/cookie";
import { IGoodSaveParam, IRequestArticleParam, ISingleArticle } from "../../interface/Article";
import { deleteHandle, getArticles } from "../../service/article";
import { ITab } from "../../interface/tab";
import { Delete } from "../../source/svgs";
// import { BMapGL } from 'react-bmap'

export default function UserContent() {
  const colorArr = ['#e85724', '#afcd50', '#1195db', '#7e53e0', '#db639b', '#8a8a8a', '#6eb960', '#83c6c2', '#e9ac8b', '#d3a8b2']
  const [city, setCity] = useState<string>('')
  const [sex, setSex] = useState<'male' | 'female' | 'secret'>('secret')
  const [age, setAge] = useState<string>('0')
  const [slogan, setSlogan] = useState<string>('')
  const [nickname, setNickname] = useState<string>('')
  const [onChange, setOnChange] = useState<boolean>(false)
  const [userInfo, setUserInfo] = useState<UserInfo>(originUserInfo)
  const [changeAvatar, setChangeAvatar] = useState<boolean>(false)
  const [avatar, setAvatar] = useState<File>()
  const [avatarSrc, setAvatarSrc] = useState<string>("")
  const [articles, setArticles] = useState<ISingleArticle[]>([])
  const [focusInfo, setFocusInfo] = useState<UserInfo[]>()
  const [canDelArticle, setCanDelArticle] = useState<boolean>(false)
  const navigate = useNavigate()

  const sexSelect: { value: string, text: string }[] = [
    {
      value: "male",
      text: "男"
    }, {
      value: "female",
      text: "女",
    }, {
      value: "secret",
      text: "暂时保密"
    }
  ]

  useEffect(() => {
    if (avatar !== undefined) {
      const read = new FileReader()
      read.readAsDataURL(avatar as Blob)
      read.onload = (e) => {
        const content: string = e.target?.result as string
        handleChangeAvatar({ account: userInfo.account, avatar: content })
        setAvatarSrc(content)
      }
    }
    // eslint-disable-next-line
  }, [avatar])

  useEffect(() => {
    const storedName = userStore.getState()
    if (typeof (storedName) === "string") {
      initUserInfo(storedName)
    } else {
      const localName = sessionStorage.getItem("stageUser")?.toString()
      if (!!localName) {
        initUserInfo(localName)
      } else {
        alert("账号未登录，点击确定跳转登陆页面")
        navigate("/login")
      }
    }
    // eslint-disable-next-line
  }, [navigate])

  function getCityName() {
    getLocation()
  }

  async function handleChangeAvatar(params: IChangeAvatar) {
    const data = await changeAvatarHandle(params)
    if (data.stat === 'ok') {
      myTip("修改成功", "success")
      return true
    } else {
      myTip(data.msg, 'fail')
      return false
    }
  }

  function getLocation() {
    const geolocation = new window.BMapGL.Geolocation()
    geolocation.getCurrentPosition(function (r) {
      // r为根据ip获取的当前的位置信息，lng为经度，lat为维度
      const point = new window.BMapGL.Point(r.point.lng, r.point.lat)
      var gc = new window.BMapGL.Geocoder()
      // 调用api使用经纬度获取具体城市信息
      gc.getLocation(point, function (res) {
        setCity(res.addressComponents.city)
      })
    })
  }

  async function getUserArticles(params: IRequestArticleParam) {
    const data = await getArticles(params)
    if (data.stat === 'ok') {
      setArticles(data.data.data)
    } else {
      myTip(data.msg, 'fail')
    }
  }

  async function initUserInfo(account: string) {
    const data = await getUserInfo({ account: account }, cookieStore.getState().toString())
    if (data.stat === 'ok') {
      const userInfo = data.data
      setUserInfo(userInfo)
      setAge(userInfo.age)
      setSex(userInfo.sex)
      setCity(userInfo.city)
      setSlogan(userInfo.slogan)
      setNickname(userInfo.nickname)
      getUserArticles({ authorId: userInfo.id })
      getAllFocusUser({ focus: userInfo.focus })
    } else {
      alert("请先登录")
      navigate("/login")
    }
  }

  async function getAllFocusUser(params: { focus: string[] }) {
    const data = await getFocuseInfo(params)
    if (data.stat === 'ok') {
      setFocusInfo(data.data)
    }
  }

  async function handleChangeInfo() {
    const changeInfo: ChangeAccount = {
      nickname: nickname,
      slogan: slogan,
      age: age,
      city: city,
      sex: sex,
      account: userInfo.account
    }
    const data = await changeAccount(changeInfo)
    if (data.stat === 'ok') {
      setUserInfo({ ...userInfo, ...changeInfo })
      alert("修改成功")
      setOnChange(false)
    } else {
      alert("修改失败，" + data.msg)
    }
  }


  async function handleDelArticle(params: IGoodSaveParam) {
    // throw new Error("Function not implemented.");
    const data = await deleteHandle(params)
    if (data.stat === 'ok') {
      getUserArticles({ authorId: userInfo.id })
      message.success('删除成功')
    } else {
      message.error(data.msg)
    }
  }


  function handleToUserPage(user: string) {
    // throw new Error("Function not implemented.");
    navigate("/userInfo/userId=" + user)
  }

  function handleArticleDetail(id: string) {
    navigate("/article/id=" + id)
  }

  return (
    <React.Fragment>
      <div className={style.mainContent} >
        <div className={style.basicInfo}>
          <div>
            <div className={style.nicknameBox} >
              <span>{userInfo.nickname}</span>
            </div>
            <div className={style.avatarBox}>
              <img
                className={style.avatar}
                onMouseEnter={() => {
                  setChangeAvatar(true)
                }}
                src={avatarSrc || userInfo.avatar || NoAvatar}
                alt='#'
              />
              {!changeAvatar ?
                (<div></div>) :
                (<div
                  className={style.banner}
                  onMouseLeave={() => {
                    setChangeAvatar(false)
                  }}
                >
                  <span className={style.avatarTip}>
                    更换头像
                  </span>
                  <input
                    type={"file"}
                    accept={'image/*'}
                    onChange={(value) => {
                      setAvatar(value.target.files![0])
                    }}
                    className={style.inputAvatar}
                  />
                </div>
                )
              }
            </div>
          </div>
          <div>
            <span>{userInfo.account} | {"ID:" + userInfo.id}</span>
          </div>
        </div>
        <div className={style.detailInfo}>
          <div className={style.titlebar}>
            <span className={style.title}>基本信息</span>
            <span
              onClick={() => {
                setOnChange(!onChange)
              }}
              className={style.changeTip}
            >
              {onChange ? "取消修改" : "点击此处修改"}
            </span>
          </div>
          <div className={style.showInfo}>
            <div>
              <span>昵称：</span>
              {!onChange ?
                (<span>{userInfo.nickname}</span>) :
                (<input value={nickname}

                  onChange={(value) => {
                    setNickname(value.target.value)
                  }}
                  className={style.inputBar}
                />)
              }
            </div>
            <div>
              <span>个性签名：</span>
              {!onChange ?
                (<span>{userInfo.slogan}</span>) :
                (<input
                  className={style.inputBar}
                  style={{
                    "width": "60px"
                  }}
                  value={slogan}
                  onChange={(value) => {
                    setSlogan(value.target.value)
                  }}
                />)
              }
            </div>
            <div className={style.selectLine}>
              <span>性别：</span>
              {!onChange ?
                (<span>{(sexSelect.find((item) => item.value === userInfo.sex))?.text}</span>) :
                (<Radio.Group value={sex} onChange={(value) => { setSex(value.target.value) }} >
                  {sexSelect.map((item) => (
                    <Radio key={item.value} value={item.value}>{item.text}</Radio>
                  ))}</Radio.Group>)}
            </div>
            <div className={style.selectLine}>
              <span>所在城市：</span>
              {!onChange ?
                (<span>{userInfo.city}</span>) :
                (<><span
                  className={style.selectBar}
                  onClick={() => {
                    getCityName()
                  }}
                >
                  定位
                </span>
                  <span>{city || "暂未定位"}</span>
                </>)
              }
            </div>
            <div className={style.selectLine}>
              <span>年龄：</span>
              {!onChange ?
                (<span>{userInfo.age}</span>) :
                (<><Input
                  value={age}
                  style={{
                    "width": "60px"
                  }}
                  onChange={(value) => {
                    setAge(value.target.value)
                  }}
                />
                  {/* <span className={style.ageShow}>{age}</span> */}
                </>)
              }
            </div>
            <div>
              <span>用户级别：{(userInfo.role.length === 0) ? "普通用户" : "官方用户"}</span>
            </div>
            <div>
              <span>注册时间：</span>
              <span>{formatTime(userInfo.createAt, "ONLY_DAY")}</span>
            </div>
            <div>
              <span>账号：</span>
              <span>{userInfo.account}</span>
            </div>
            <div>
              <span>ID：</span>
              <span>{userInfo.id}</span>
            </div>
            <div>
              <span>账号积分：</span>
              <span>{userInfo.score}</span>
            </div>
            {onChange ?
              (<span onClick={() => { handleChangeInfo() }} className={style.confirmBtn}>确认当前修改</span>) :
              (<div></div>)
            }
          </div>
        </div>
        <div className={style.userArticle}>
          <div className={style.myArticle}>
            <span className={style.title}>我的文章</span>
            <span onClick={() => { setCanDelArticle(!canDelArticle) }}>{canDelArticle ? "取消" : "删除"}</span>
          </div>
          <div>
            {articles.length === 0 ?
              <div className={style.empty}>
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={false} />
                <div>该板块还没有任何数据哦，<span onClick={() => { navigate("/create") }}>点击进行发布？</span></div>
              </div> :
              articles.map((article: ISingleArticle, index: number) => (
                <div
                  className={style.block}
                  key={article.id + index}
                >
                  <div
                    onClick={(value) => {
                      handleArticleDetail(article.id)
                    }}>
                    <div className={style.info}>
                      <div className={style.titleBar}>
                        <div>{article.title}</div>
                      </div>
                      <div className={style.tabs}>
                        {article.tabs.map((tab: ITab, index: number) => (
                          <div
                            style={{ "backgroundColor": colorArr[Math.floor(Number((Math.random() * 10)))] }}
                            className={style.tab}
                            key={tab.value + index}
                          >
                            <span>{tab.lable}</span>
                          </div>
                        ))}
                      </div>
                      <div>
                        <span className={style.publishTime}>
                          {`发布于${formatTime(article.create_Ts, 'ONLY_DAY')}`}
                        </span>
                      </div>
                    </div>
                    {index === articles.length - 1 ? <></> : <div className={style.divide}></div>}
                  </div>
                  {canDelArticle ? <Popconfirm
                    title="确定删除该文章?"
                    onConfirm={() => handleDelArticle({ type: 'article', userId: userInfo.id, articleId: article.id })}
                    okText="Yes"
                    cancelText="No"
                  ><div className={style.deleteBg}>
                      <img src={Delete} alt="" />
                    </div></Popconfirm> : <></>}
                </div>
              ))}
          </div>
        </div>
        <div className={style.focusList}>
          <div className={style.title}>{"我的关注"}</div>
          <div className={style.users}>
            {focusInfo?.length === 0 ? <Empty /> : focusInfo?.map((user: UserInfo) => (
              <div onClick={() => handleToUserPage(user.id)} className={style.singleUser} key={user.account + user.id}>
                <img className={style.focusAvatar} src={user.avatar || NoAvatar} alt={user.nickname} />
                <div className={style.focusName}>{user.nickname}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </React.Fragment >
  )
}
